var options = {
};
var lottery = new Lottery(options);

var lotteryEl = document.querySelector(".item-container");

var dialogEl = document.querySelector(".lottery_modal");

var gift = 'bug'

var giftArr = [0, 0, 0, 0, 0, 0, 0, 0]



function removeChosenClass() {
  var el = lotteryEl.querySelector('.turntable-item.chosen');
  if (el) {
    el.classList.remove('chosen');
  }
}

function addChosenClass(index) {
  lotteryEl.querySelector('.turntable-item.turntable-item-' + index).classList.add('chosen');
}

lottery.onStart = function (ins, index, cycle) {
  removeChosenClass();
  addChosenClass(index);
}

lottery.onUpdate = function (ins, index, times) {
  removeChosenClass();
  addChosenClass(index);
}

lottery.onEnded = function (ins, index, prizeIndexes) {
  removeChosenClass();
  addChosenClass(index);
  dialogEl.querySelector('.desc-gift').textContent = gift + '一个，请联系管理员兑换！！'
  setTimeout(function () {
    dialogEl.classList.remove("hide");
  }, 500)
}

lottery.onError = function (ins, code, message) {
  console.log('onError', code, message)
}

var btnStart = document.querySelector(".turntable-box .turntable-item.lottery");
btnStart.addEventListener('click', function () {
  lottery.start();
  setTimeout(() => {
    setPrize();
  }, 800)
})


btnSubmit.addEventListener('click', function () {
  dialogEl.classList.add("hide");
})

function setPrize() {
  const arr = ['66矿石', '随机限量徽章', '掘金新款T恤', '乐高海洋巨轮', 'Switch', 'Yoyo抱枕', '掘金鼠标垫', 'Bug']
  // const randomNum = Math.floor(Math.random() * 8)
  const randomNum = getGift()
  // console.log(randomNum)
  gift = arr[randomNum]
  giftArr.splice(randomNum, 1, giftArr[randomNum] + 1)
  // giftArr.push(gift)
  lottery.setPrize([randomNum])
}

function getGift() {
  const weightRatio = [1, 1, 1, 1, 1, 1, 1, 1]
  const total = weightRatio.reduce((prev, curr) => {
    return prev + curr
  })
  let randomNum = Math.random() * total
  for (let i = 0; i < weightRatio.length; i++) {
    if (randomNum < weightRatio[i]) {
      return i
    } else {
      randomNum -= weightRatio[i]
    }
  }
}

// var lookGift = document.querySelector(".main-look");
// lookGift.addEventListener('click', function () {
//   if (!giftArr || giftArr.length === 0) {
//     alert('暂时没有收获，先去抽奖吧！')
//   } else {
//     let str = ''
//     giftArr.forEach((item, index) => {
//       str += (index ? ',' : '') + item + '\n'
//     })
//     alert(str)
//   }
// })
var lookGift = document.querySelector(".main-look");
lookGift.addEventListener('click', function () {
  const flag = giftArr.some(item => {
    return item !== 0
  })
  if (flag) {
    const arr = ['66矿石', '随机限量徽章', '掘金新款T恤', '乐高海洋巨轮', 'Switch', 'Yoyo抱枕', '掘金鼠标垫', 'Bug']
    const total = giftArr.reduce((prev, curr) => {
      return prev + curr
    })
    let str = '恭喜总计中奖' + total + '个，其中：' + '\n'
    giftArr.forEach((item, index) => {
      if (item != 0) {
        str += arr[index] + '*' + item + '\n'
      }
    })
    alert(str)
  } else {
    alert('暂时没有收获，先去抽奖吧！')
  }
})
